package com.kedacom.ctsp.authz.oauth2.client.provider;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @com.kedacom.ctsp.authz.oauth2.client.provider
 * @fenghaiju
 * @2018/5/14-13:33
 * @cloud-rbac
 **/
@Slf4j
public class RestLogoutHandler implements LogoutHandler {
    private boolean invalidateHttpSession = true;
    private boolean clearAuthentication = true;

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        Assert.notNull(httpServletRequest, "HttpServletRequest required");
        if (this.invalidateHttpSession) {
            HttpSession session = httpServletRequest.getSession(false);
            if (session != null) {
                log.debug("Invalidating session: " + session.getId());
                session.invalidate();
            }
        }
        if (this.clearAuthentication) {
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication(null);
        }

        SecurityContextHolder.clearContext();
    }
}
